# Copyright (c) 2023 Presto Labs Pte. Ltd.
# Author: tianqiang

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo

# filter because bitmart have 100 topics subscription limit for each websocket connection
# https://developer-pro.bitmart.com/en/spot/#stay-connected-and-limit
# copy from data/coin2/feed/symbol_groups.toml
enable_symbol_set = { "CCX-USDT", "WEMIX-USDT", "BTC-USDT", "ETH-USDT", "BNB-USDT", "XRP-USDT", "ADA-USDT", "MATIC-USDT" }

def generate():
  mea = 'Spot.Bitmart.v3'
  me = 'Spot.Bitmart'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  currency_pair_data = requests.get('https://api-cloud.bitmart.com/spot/v1/symbols').json()['data']['symbols']
  data = requests.get("https://api-cloud.bitmart.com/spot/v1/symbols/details").json()['data']['symbols']

  pis = []
  for info in data:
    native_symbol: str = info['symbol']
    if native_symbol not in currency_pair_data:
      continue
    native_base = info['base_currency']
    native_quote = info['quote_currency']
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)

    if base[0] == '$':
      base = base[1:]
    
    symbol = "%s-%s" % (base, quote)

    if symbol not in enable_symbol_set:
      continue

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=1.0 / pow(10, int(info['price_max_precision'])),
        qty_ticksize=float(info['quote_increment']),
        min_qty=float(info['base_min_size']),
        min_amount=max(float(info['min_buy_amount']), float(info['min_sell_amount'])),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  base_currency_list = [info['native_base'] for info in data]
  quote_currency_list = [info['native_quote'] for info in data]
  balance_currency_list = [
      info['native_base'] for info in data if info['quote'] == 'USD'] + ['USDT']
  inverse_symbol_list = [
      info['native_symbol'] for info in data if info['quote'] == 'USD']
  usdt_symbol_list = [
      info['native_symbol'] for info in data if info['quote'] == 'USDT']
  res = {
      'base_currency_list': list(set(base_currency_list)),
      'quote_currency_list': list(set(quote_currency_list)),
      'balance_currency_list': list(set(balance_currency_list)),
      'inverse_symbol_list': list(set(inverse_symbol_list)),
      'usdt_symbol_list': list(set(usdt_symbol_list)),
  }
  return res


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
